package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/scottq/go-framework/src/utils"
	v1http "gitee.com/scottq/go-framework/src/v1/httpserver"
	v1log "gitee.com/scottq/go-framework/src/v1/log"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

func main() {
	name := "example"
	logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))

	logger := v1log.NewZapLog(name, logPath, nil)
	httpServer, err := v1http.NewHttpServer("", ":8080")
	if err != nil {
		logger.Error("run http server error:%s" + err.Error())
		return
	}
	//添加logger
	httpServer.AddLogger(logger)

	//注册简单的路由
	httpServer.RouteGet("/v1", Index, []v1http.Middleware{
		RequestIdMiddleware,
		ResponseMiddleware,
	})
	httpServer.RouteGet("/v1/check", Index, []v1http.Middleware{
		CheckMiddleware,
	})

	logger.Fatal(httpServer.Run().Error())
}

//http router
func Index(ctx *v1http.Ctx) {
	ctx.SetMsg("self defined response")
	ctx.SetData(map[string]interface{}{})
	ctx.Response()
}

//中间件中设置 检查传参
var CheckMiddleware v1http.Middleware = func(ctx *v1http.Ctx, next func(*v1http.Ctx)) {

	form:=ctx.Form()
	user := form.Get("user")
	password := form.Get("password")
	println("params:", user, password)

	if user == "admin" && password == "admin" {
		next(ctx)
	}
}

//中间件中设置 添加 RequestId
var RequestIdMiddleware v1http.Middleware = func(ctx *v1http.Ctx, next func(*v1http.Ctx)) {
	ctx.WithValue("RequestId", utils.NewRequestId())
	next(ctx)
}

//中间件中设置 自定义response处理器
var ResponseMiddleware v1http.Middleware = func(ctx *v1http.Ctx, next func(*v1http.Ctx)) {
	requestId := ctx.Value("RequestId").(string)
	ctx.SetResponseHandler(NewResponseHandler(ctx.Writer(), requestId))
	next(ctx)
}

//自定义的返回格式
type DefinedResponse struct {
	data   map[string]interface{}
	writer http.ResponseWriter
}

func NewResponseHandler(writer http.ResponseWriter, requestId string) *DefinedResponse {
	return &DefinedResponse{
		data: map[string]interface{}{
			"time":      time.Now().UnixNano(),
			"requestId": requestId,
		},
		writer: writer,
	}
}

func (resp *DefinedResponse) SetCode(code int64) {
	resp.data["code"] = code
}

func (resp *DefinedResponse) SetMsg(msg string) {
	resp.data["message"] = msg
}

func (resp *DefinedResponse) SetData(data interface{}) {
	resp.data["data"] = data
}

func (resp *DefinedResponse) SetRequestId(requestId string) {
	resp.data["request_id"] = requestId
}

func (resp *DefinedResponse) GetCode() int64 {
	return resp.data["code"].(int64)
}

func (resp *DefinedResponse) GetMsg() string {
	return resp.data["message"].(string)
}

func (resp *DefinedResponse) GetData() interface{} {
	return resp.data["data"]
}

func (resp *DefinedResponse) GetRequestId() string {
	return resp.data["request_id"].(string)
}

func (resp *DefinedResponse) Response(params ...interface{}) {
	s, _ := json.Marshal(resp.data)
	resp.writer.Write(s)
}
